import { axioswnewmedical } from '@/http/axiosWrite';
import { axiosrnewmedical } from '@/http/axiosRead';
import { showNotify } from 'vant';

// 支付方式枚举
export enum PaymentMethod {
  BALANCE = 'balance',
  MEDICAL = 'medical'
}

// 项目类型枚举
export enum ItemType {
  DRUG = 1,
  CHECKUP = 2,
  TEST = 3
}

// 支付结果接口
export interface PaymentResult {
  success: boolean;
  message: string;
  prescriptionApplicationId?: number;
}

// 支付项目接口
export interface PaymentItem {
  itemId: number;
  itemType: ItemType;
  amount: number;
  quantity: number;
}

// 支付参数接口
export interface PaymentParams {
  patientId: number;
  items: PaymentItem[];
  paymentMethod: PaymentMethod;
  cashierId: number;
}

// 申请记录接口
interface PrescriptionApplication {
  id: number;
  hospitalId: number;
  hospitalName: string;
  userId: number;
  userName: string | null;
  applicationTime: string;
  status: number;
  statusName: string;
  totalAmount: number;
  applyReason: string;
  auditorId: number;
  auditorName: string | null;
  auditTime: string | null;
  rejectReason: string | null;
  paymentTime: string | null;
  cancelTime: string | null;
  details: unknown;
}

/**
 * 支付工具类
 */
export class PaymentHelper {
  
  /**
   * 获取患者的申请记录ID
   */
  static async getPrescriptionApplicationId(patientId: number): Promise<number> {
    try {
      // 首先尝试从localStorage获取当前申请ID
      const currentApplicationId = localStorage.getItem('currentPrescriptionApplicationId');
      if (currentApplicationId) {
        const applicationId = parseInt(currentApplicationId, 10);
        if (!isNaN(applicationId) && applicationId > 0) {
          console.log('使用当前申请ID:', applicationId);
          return applicationId;
        }
      }
      
      // 如果没有当前申请ID，则从API查找
      const response = await axiosrnewmedical.get('/Prescription/GetPrescriptionApplications', {
        params: {
          pageIndex: 1,
          pageSize: 10,
          includeDetails: false
        }
      });
      
      if (response.data.code === 200 && response.data.data.length > 0) {
        const patientApplications: PrescriptionApplication[] = response.data.data.filter(
          (app: PrescriptionApplication) => app.userId === patientId
        );
        
        if (patientApplications.length > 0) {
          // 优先选择待审核状态的申请记录
          const pendingApplication = patientApplications.find((app: PrescriptionApplication) => app.status === 0);
          const selectedApplication = pendingApplication || patientApplications[0];
          
          console.log('找到现有申请记录:', selectedApplication);
          return selectedApplication.id;
        } else {
          throw new Error('未找到该患者的申请记录，请先提交开单申请');
        }
      } else {
        throw new Error('获取申请列表失败');
      }
    } catch (error) {
      console.error('获取申请记录ID失败:', error);
      throw error;
    }
  }

  /**
   * 执行支付
   */
  static async executePayment(params: PaymentParams): Promise<PaymentResult> {
    try {
      const { patientId, items, paymentMethod, cashierId } = params;
      
      // 按类型分组项目
      const drugItems = items.filter(item => item.itemType === ItemType.DRUG);
      const checkupItems = items.filter(item => item.itemType === ItemType.CHECKUP);
      const testItems = items.filter(item => item.itemType === ItemType.TEST);
      
      // 获取申请记录ID
      const prescriptionApplicationId = await this.getPrescriptionApplicationId(patientId);
      
      // 构建支付请求
      const paymentPromises: Promise<{ data: { code: number; msg?: string } }>[] = [];
      
      const payChannel = paymentMethod === PaymentMethod.BALANCE ? "自费支付" : "医保支付";
      
      // 药品支付
      if (drugItems.length > 0) {
        const drugPaymentData = {
          patientId: patientId,
          inputPatientId: patientId,
          prescriptionApplicationId: prescriptionApplicationId,
          prescriptionIds: drugItems.map(item => item.itemId),
          amount: drugItems.reduce((sum, item) => sum + item.amount, 0),
          payChannel: payChannel,
          cashierId: cashierId
        };
        
        paymentPromises.push(
          axioswnewmedical.post('/Payment/PayForDrugs', drugPaymentData)
        );
      }

      // 检查支付
      if (checkupItems.length > 0) {
        const checkupPaymentData = {
          patientId: patientId,
          inputPatientId: patientId,
          prescriptionApplicationId: prescriptionApplicationId,
          laborderIds: checkupItems.map(item => item.itemId),
          amount: checkupItems.reduce((sum, item) => sum + item.amount, 0),
          payChannel: payChannel,
          cashierId: cashierId
        };
        
        paymentPromises.push(
          axioswnewmedical.post('/Payment/PayForCheckup', checkupPaymentData)
        );
      }

      // 检验支付
      if (testItems.length > 0) {
        const testPaymentData = {
          patientId: patientId,
          inputPatientId: patientId,
          prescriptionApplicationId: prescriptionApplicationId,
          laborderIds: testItems.map(item => item.itemId),
          amount: testItems.reduce((sum, item) => sum + item.amount, 0),
          payChannel: payChannel,
          cashierId: cashierId
        };
        
        paymentPromises.push(
          axioswnewmedical.post('/Payment/PayForTest', testPaymentData)
        );
      }

      // 执行所有支付请求
      console.log('开始执行支付请求，共', paymentPromises.length, '个');
      const results = await Promise.all(paymentPromises);
      
      // 检查支付结果
      const failedResults = results.filter(result => {
        return !result.data || result.data.code !== 200;
      });
      
      if (failedResults.length > 0) {
        const errorMessages = failedResults
          .map(result => result.data?.msg || '支付失败')
          .join('; ');
        throw new Error(errorMessages);
      }
      
      return {
        success: true,
        message: '支付成功',
        prescriptionApplicationId: prescriptionApplicationId
      };
      
    } catch (error) {
      console.error('支付执行失败:', error);
      
      let errorMessage = '支付失败，请稍后再试';
      
      if (error instanceof Error) {
        errorMessage = error.message;
      } else if (typeof error === 'object' && error !== null) {
        const axiosError = error as { response?: { data?: { msg?: string }; status?: number } };
        if (axiosError.response?.data?.msg) {
          errorMessage = axiosError.response.data.msg;
        } else if (axiosError.response?.status) {
          errorMessage = `网络错误: ${axiosError.response.status}`;
        }
      }
      
      return {
        success: false,
        message: errorMessage
      };
    }
  }

  /**
   * 显示支付结果通知
   */
  static showPaymentNotification(result: PaymentResult) {
    if (result.success) {
      showNotify({ 
        type: 'success', 
        message: result.message,
        duration: 3000
      });
    } else {
      showNotify({ 
        type: 'danger', 
        message: result.message,
        duration: 5000
      });
    }
  }

  /**
   * 验证支付参数
   */
  static validatePaymentParams(params: PaymentParams): { isValid: boolean; message: string } {
    if (!params.patientId || params.patientId <= 0) {
      return { isValid: false, message: '患者ID无效' };
    }
    
    if (!params.items || params.items.length === 0) {
      return { isValid: false, message: '没有可支付的项目' };
    }
    
    if (!params.cashierId || params.cashierId <= 0) {
      return { isValid: false, message: '收银员ID无效' };
    }
    
    const totalAmount = params.items.reduce((sum, item) => sum + item.amount, 0);
    if (totalAmount <= 0) {
      return { isValid: false, message: '支付金额必须大于0' };
    }
    
    return { isValid: true, message: 'valid' };
  }
} 